<template>
  <div class="app-container">
<!--     顶部搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="originalFileName">
        <el-input
          v-model="queryParams.originalFileName"
          placeholder="请输入文件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="contentType">
        <el-select v-model="queryParams.contentType" placeholder="请选择文件类型" clearable size="small">
          <el-option
            v-for="dict in contentTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文件标签" prop="paramLabels">
        <el-cascader
          :show-all-levels="false"
          v-model="queryParams.paramLabels"
          filterable
          clearable
          :options="allLabelOptions"
          :props="cascaderProps"
          @change="handleChange"></el-cascader>

      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>

      </el-form-item>
    </el-form>
<!--    文件路径 与 汇总信息 -->
    <el-row type="flex" class="row-bg" justify="space-around">
      <el-col :span="6"><div class="grid-content bg-purple">
<!--        隐藏过长路径-->
        <el-dropdown v-if="directoryListOlder.isNotEmpty">
        <span class="el-dropdown-link">
           <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
          <el-dropdown-menu slot="dropdown" >
            <el-dropdown-item v-for="(item, index) in directoryListOlder" v-bind:key="item.name" @click.native="goToThisUrl(item)">{{item.name}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-link  type="primary line-height:1.7 font-weight:bold" v-for="(item, index) in directoryList" v-bind:key="item.name"  @click.native="handleLink(item)">{{item.name}}</el-link>
      </div></el-col>
      <el-col :span="6"><div class="grid-content bg-purple-light">
        <span>桶内对象数量： {{fileTotalInfo.totalFileInfo}}  <el-divider direction="vertical"></el-divider>  存储总量： {{fileTotalInfo.fileSize.toFixed(2)}} {{fileTotalInfo.unit}} </span>
      </div></el-col>
      <el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
    </el-row>
<!--    功能按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-back"
          @click="handleBack"
        >后退</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-document-add"
          @click="handleAddFile"
        >上传素材</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-folder-add"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['file:flie:add']"
        >创建文件夹</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['file:flie:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
<!--      表格 -->
    <el-table v-loading="loading" :data="flieList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="文件名称" align="center" prop="originalFileName" >
<!--        简单的逻辑判断是否为文件夹 -->
<!--        如果是文件夹 设置按钮格式-->
        <template slot-scope="scope">
          <div v-if="showSwiper(scope.row)">
            <el-button
              size="mini"
              type="text"
              @click="handleLook(scope.row)"
            ><span>{{ scope.row.originalFileName}}</span></el-button>
          </div>
          <div v-else>
            <span>{{ scope.row.originalFileName}}</span>
          </div>
          <el-popover trigger="hover" placement="right">
            <p>记录id: {{ scope.row.id }}</p>
            <p>文件名称：{{ scope.row.originalFileName }}</p>
            <p>记录类型: {{ scope.row.contentType }}</p>
            <p>文件大小: {{ scope.row.fileSize }}</p>
            <p>路径：{{ scope.row.pathFileName }}</p>
            <p>上传者: {{ scope.row.createBy }}</p>
            <p>上传时间: {{ scope.row.createTime }}</p>
            <p>修改人: {{ scope.row.updateBy }}</p>
            <p>修改时间: {{ scope.row.updateTime }}</p>
            <div slot="reference" class="name-wrapper">
              <el-button type="text">{{ scope.row.userName }}</el-button>
            </div>
          </el-popover>
        </template>

      </el-table-column>
      <el-table-column label="文件标签" align="center" prop="labels" >
        <template slot-scope="scope">
          <el-tag
            :key="tag"
            size="small"
            v-for="tag in  scope.row.labels"
            :disable-transitions="false"
          >
            {{tag}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="文件类型" align="center" prop="contentType" :formatter="contentTypeFormat" />
      <el-table-column label="文件大小" align="center" prop="fileSize" :formatter="calculateFileSize" />
<!--      <el-table-column label="文件路径" align="center" prop="pathFileName" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['file:flie:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['file:flie:remove']"
          >删除</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handlePreview(scope.row)"
              v-if="!showSwiper(scope.row)"
            >预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDownload(scope.row)"
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog id ="uploadFile"  :visible.sync="openFile" width="500px" append-to-body>
    <el-tabs v-model="defaultTab" type="border-card" style="border: 0px;" stretch >
<!--    <el-tabs v-model="defaultTab">-->
      <el-tab-pane label="上传文件" name="first">
        <!-- 上传文件弹窗  -->
        <div id ="uploadFiles">
          <el-form ref="form"  :rules="rules" label-width="80px">
            <el-form-item label="上传路径" >
              <treeselect v-model="fileObject.pcode" :props="defaultProps"  :options="materialOptions" :show-count="true" placeholder="请选择路径" />
            </el-form-item>
            <el-form-item label="素材">
              <el-upload
                ref="uploadImg"
                :limit="1"
                list-type="picture-card"
                accept="image/*"
                :action="uploadImg.url"
                :headers="uploadImg.headers"
                :file-list="uploadImg.fileList"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                :data="fileObject"
                :before-upload="uploadImgBeforeUpload">
                <i class="el-icon-plus"></i>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="标记文本">
              <el-upload ref="uploadTxt"
                         :limit="1"
                         accept=".txt"
                         :action="uploadTxt.url"
                         :file-list="uploadTxtfileList"
                         :headers="uploadTxt.headers"
                         :on-progress="handleFileUploadProgress"
                         :on-success="handleFileSuccess"
                         :auto-upload="false"
                         :data="fileObject"
                         :before-upload="uploadTxtBeforeUpload">
                <el-button size="small" type="primary" icon="el-icon-upload">选择txt文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的.txt文件</div>
              </el-upload>
            </el-form-item>


            <el-form-item label="添加标签">
              <el-cascader
                :show-all-levels="false"
                v-model="fileObject.selectedLabel"
                filterable
                clearable
                :options="allLabelOptions"
                :props="cascaderProps"
                @change="handleChange"></el-cascader>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button style="margin-left: 10px;" size="small" type="success" :loading="uploadImg.isUploading" @click="submitUpload" >上传到服务器</el-button>
            <el-button @click="cancel" class="mini">取 消</el-button>
          </div>
        </div>
      </el-tab-pane>


      <el-tab-pane label="上传文件夹" name="second">
        <div id ="uploadZipFiles">
          <el-form ref="form" :rules="rules" label-width="80px">
            <el-form-item label="上传路径">
              <treeselect v-model="fileObject.pcode" :props="defaultProps" :options="materialOptions" :show-count="true"
                          placeholder="请选择路径"/>
            </el-form-item>
            <el-form-item label="压缩文件">
              <el-upload ref="upload"
                         :limit="1"
                         accept=".zip"
                         :action="uploadZip.url"
                         :file-list="uploadZip.fileList"
                         :headers="uploadZip.headers"
                         :on-progress="handleFileZipUploadProgress"
                         :on-success="handleZipFileSuccess"
                         :auto-upload="false"
                         :data="fileObject"
              >
                <el-button size="small" type="primary" icon="el-icon-upload">压缩文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的.zip文件</div>
              </el-upload>
            </el-form-item>


            <el-form-item label="添加标签">
              <el-cascader
                :show-all-levels="false"
                v-model="fileObject.selectedLabel"
                filterable
                clearable
                :options="allLabelOptions"
                :props="cascaderProps"
                @change="handleChange"></el-cascader>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button style="margin-left: 10px;" size="small" type="success" :loading="uploadImg.isUploading"
                       @click="submitZipUpload">上传到服务器
            </el-button>
            <el-button @click="cancel" class="mini">取 消</el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    </el-dialog>




    <!-- 添加或修改文件记录 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

<!--      <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>-->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="originalFileName">
          <el-input v-model="form.originalFileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="路径" prop="pcode">
          <treeselect v-model="fileObject.pcode" :props="defaultProps"  :options="materialOptions" :show-count="true" placeholder="请选择路径" />
        </el-form-item>
        <el-form-item label="添加标签">
          <el-cascader
            :show-all-levels="false"
            v-model="fileObject.selectedLabel"
            filterable
            clearable
            :options="allLabelOptions"
            :props="cascaderProps"
            @change="handleChange"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


<!--    <img src="https://img2.baidu.com/it/u=4033504488,813972093&fm=26&fmt=auto&gp=0.jpg">-->
    <!-- 图片显示 -->
    <el-dialog :title="title" :visible.sync="openShow" append-to-body >
      <el-carousel indicator-position="outside" height="500px" arrow="always">
        <el-carousel-item label=" 原 图 " style="font-size: 14px;color: black">
          <div  v-viewer class="block" v-for="fit in fits" :key="fit" style="text-align: center;width: 100%;height: 100%;">
            <el-image
              style="width: 100%; height: 100%"
              :src="img_url"
              :fit="fit"></el-image>
          </div>
        </el-carousel-item>
        <el-carousel-item label="标注图" style="font-size: 14px">
<!--          <div v-viewer @dblclick="onclickSecond">-->
<!--          <canvas ref="myCanvas" id="mycanvas" style="width: 100%; height: 100%" @dblclick="onclickSecond"></canvas>-->
<!--          </div>-->
          <div  v-viewer class="block" v-for="fit in fits" :key="fit" style="text-align: center;width: 100%;height: 100%;">
            <el-image
              style="width: 100%; height: 100%"
              :src="tagImageUrl"
              :fit="fit"></el-image>
          </div>
        </el-carousel-item>
      </el-carousel>


    </el-dialog>
    <el-drawer
      title=""
      :visible.sync="drawer"
      :with-header="false">
      <span>我来啦!</span>
    </el-drawer>
    <!-- 视频显示 -->
    <el-dialog :title="title" :visible.sync="openShowVedio"  append-to-body>
      <div style="text-align: center;width: 100%;height: 100%;">
        <video   class="video-player vjs-custom-skin" :preload="preload"
                  :poster="videoImg" :height="height" :width="width" align="center" :controls="controls"  :autoplay="autoplay">
          <source :src="video_url" type="video/mp4">
        </video>
      </div>
    </el-dialog>
  </div>
<!--  测试 图片 画图  -->



</template>

<script>
import {
  listFlie,
  getTableFlie,
  getFlie,
  delFlie,
  addFlie,
  updateFlie,
  exportFlie,
  getTotal,
  addFolder,
  downFile,
  getSelectTree,
  downloadFile,
  downloadFlie,
  getLabelSelectTree, transferYolo
} from "@/api/file/flie";
import {addLabelList, listLabel} from "@/api/file/label";
import {getFileLabel} from "@/api/material/label";
import {listTag_file,getTagImage} from "@/api/file/tag_file";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import treeUtil from "@/api/material/tree";

export default {
  name: "Flie",
  components: {
    Treeselect,
  },
  props: [],
  data() {
    return {
      saveInfo:null,
      //定义需要渲染的图片数组
      // canvasWidth: 2400, // 画布大小
      // canvasHeight: 1400,
      myCanvas: null,
      ctx: null,

      imgX: 200, // 图片在画布中渲染的起点x坐标，这个坐标为后期的添加注释图片、文字位置提供了相对坐标点
      imgY: 100,
      imgScale: 0.9, // 图片启示的缩放大小
      extraImgList: [],
      imgObject: [],  // 存放预加载好了的图片对象

      directoryListOlder: [{pcode:-1,name:"/root",code:"-1",isNotEmpty:false}],//收起来的路径
      defaultTab:"first",//上传素材弹窗默认为第一个标签页
      cascaderProps: {
        value: 'id',
        label:'label',
        children: 'children',
        expandTrigger: 'hover',
        multiple:true,

      },
      allLabelOptions:[],
      // paramLabels:[],
      labelList: [],
      //图片自适应
      fits:["fill"],
      // 画布信息
      startX: '',  //画画开始的X坐标
      startY: '',  //画画开始的Y坐标
      endX: '',    //画画结束的X坐标
      endY: '',    //画画结束的Y坐标
      isMouseDownInCanvas: '', //鼠标是否按下
      customcxt: '',      // cxt
      customRwidth: '',    //原图与展示图片的宽度比
      customRheight: '',   //原图与展示图片的高度比
      imgstyle: '',        //根据图片大小自适应样式
      canvasstyle: '',     //根据图片大小canvas自适应样式 居中显示
      canvasWidth: '',     //根据图片大小自适应canvas宽
      canvasHeight: '',    //根据图片大小自适应canvas高
      DivWidth: 1460,      //最大宽度
      DivHeight: 740,      //最大高度

      //目录树
      // 视频播放器组件
      videoSrc: '#',
      videoImg: '视频播放参数',
      playStatus: '',
      muteStatus: '',
      isMute: true,
      isPlay: false,
      width: '820', // 设置视频播放器的显示宽度（以像素为单位）
      height: '500', // 设置视频播放器的显示高度（以像素为单位）
      preload: 'auto', //  建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
      controls: true, // 确定播放器是否具有用户可以与之交互的控件。没有控件，启动视频播放的唯一方法是使用autoplay属性或通过Player API。
      autoplay: '',
      // 文件汇总细腻些
      fileTotalInfo: [],
      // 点击进去的目录链
      directoryList: [{pcode:-1,name:"/root",code:"-1"}],
      // 上传文件携带的额外信息 上传文件所在的文件夹位置 文件夹名称
      // 默认是根目录
      pcode: -1,
      // 文件上传组件
      // 上传参数
      uploadImg: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/flie/uploadFile",
        // 上传的文件列表
        fileList: [],
        filepath: null,
      },
      uploadTxt: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/flie/uploadFile",
        // 上传的文件列表
        fileList: [],
        filepath: null,
      },
      uploadZip: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file_serve/uploadZipFile",
        // 上传的文件列表
        fileList: [],
        filepath: null,
      },
      uploadTxtAction: 'https://jsonplaceholder.typicode.com/posts/',
      uploadTxtfileList: [],
      uploadZipfileList: [],
      uploadZipAction: 'https://jsonplaceholder.typicode.com/posts/',
      fileObject:{pcode:'-1',selectedLabel:[]},
      openFile: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件记录-2表格数据
      flieList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 文件类型字典
      contentTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        originalFileName: null,
        contentType: null,
        pcode: -1,
        paramLabels: null,
        label:""
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        originalFileName: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
      },
      // 预览模块
      openShow: false,
      openShowVedio: false,
      img_url: "https://img2.baidu.com/it/u=4033504488,813972093&fm=26&fmt=auto&gp=0.jpg",
      video_url: "/profile/upload/2021/07/14/963d4aa0-fca4-4eec-9d5f-b2a7729a5ced.mp4",
      tagImageUrl:"",
      // 创建文件夹
      openDir: false,
      //树形控件
      //级联选择器
      value: [],
      options: [ {
        id: 'a',
        label: 'a',
        children: [ {
          id: 'aa',
          label: 'aa',
        }, {
          id: 'ab',
          label: 'ab',
        } ],
      }, {
        id: 'b',
        label: 'b',
      }, {
        id: 'c',
        label: 'c',
      } ],
      materialOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      downloadObject: {
        fileName: '',
        delete: false,
      },
      queryTagParams: {
        pageNum: 1,
        pageSize: 10,
        fileCode: null,
        tagCategory: null,
        tagInfo: null,
        imgWidth:null,
        imgHeight:null
      },
      // 标记文件信息表格数据
      tag_fileList: [],
      tag_total: null,
      tag_id: null,
      tag_name: null,
      ifFile: true,
      drawer: false,
      openZipFile: false,
    };
  },


  created() {
    this.handleSelectTree();
    this.getList();
    this.fileObject.selectedLabel=[];
    this.getDicts("base_file_type").then(response => {
      this.contentTypeOptions = response.data;
    });
  },
  methods: {
    loadImg() {
      var canvas = document.getElementById("mycanvas")
      var context = canvas.getContext('2d');
      var _this = this;
      // let extraImgList = _this.extraImgList;
      // let length = extraImgList.length;
      var imageList = [];
      let count = 0;
      //加载底层图片，这个先后顺序一定要有，不然用来注释的图片可能会被底层图片覆盖
      var isBgLoaded = false;
      var img = new Image();
      // var bgImg = extraImgList[0];
      // img.src = bgImg.url;
      img.src = this.img_url;
      img.onload = () => {
        imageList.push({img: img, x: img.x, y: img.y, width: img.width, height: img.height});
        ++count;
        // if (length > 1) { // 加载多张图片
        //   //加载剩余图片
        //   for (let key = 1; key < length; key++) {
        //     // let item = extraImgList[key];
        //     let extarImg = new Image();
        //     extarImg.src = item.url;
        //     extarImg.onload = () => {
        //       imageList.push({img: extarImg, x: item.x, y: item.y, width: item.width, height: item.height})
        //       if (++count >= length) { // 判断是否所有的图片都被预加载完成
        //         _this.imgObject = imageList;
        //         _this.drawImage(imageList);
        //       }
        //     }
        //   }
        // } else { //只加载一张图片
          _this.imgObject = imageList;
          context.drawImage(imageList);
        // }
      }
    },
    canvasEventsInit() {
      var _this = this;
      var canvas = _this.myCanvas;
      var context=canvas.getContext('2d');
      canvas.onmousedown = function (event) {
        var imgx = _this.imgX;
        var imgy = _this.imgY;
        var pos = {x:event.clientX, y:event.clientY};  //获取相对浏览器窗口的坐标，为后期将窗口坐标转换成canvas的坐标做准备
        canvas.onmousemove = function (evt) {  //移动
          canvas.style.cursor = 'move';
          var x = (evt.clientX - pos.x) * 2 + imgx; //坐标转换
          var y = (evt.clientY - pos.y) * 2 + imgy;
          _this.imgX  = x;
          _this.imgY  = y;
          context.drawImage(_this.imgObject);  //重新绘制图片
        };
        canvas.onmouseup = function () {
          canvas.onmousemove = null;
          canvas.onmouseup = null;
          canvas.style.cursor = 'default';
        };
      };

      canvas.onmousewheel = canvas.onwheel = function (event) {    //滚轮放大缩小
        var wheelDelta = event.wheelDelta ? event.wheelDelta : (event.deltalY * (-40));  //获取当前鼠标的滚动情况
        if (wheelDelta > 0) { // 放大时，每次放大到原来的1.1倍
          _this.imgScale *= 1.1; //注意，我的缩放是以左上角位置为中心进行缩放的，如果要以图片中心为缩放点，需要修改 imgX，imgY的值
        } else {
          if(_this.imgScale > 0.9) { // 缩小到原来的0.9倍
            _this.imgScale *= 0.9;
          }
        }
        context.drawImage(_this.imgObject);   //重新绘制图片
        event.preventDefault  && event.preventDefault(); // 阻止默认事件，可能在滚动的时候，浏览器窗口也会滚动
        return false;
      };
    },
    onclickSecond(){
      // console.log("xxxxxxxxxxx")
      // this.myCanvas = this.$refs.myCanvas;
      // this.ctx = this.myCanvas.getContext('2d');
      // this.loadImg();
      // this.canvasEventsInit();

      // let canvas = document.getElementById("mycanvas");
      // let ctx=canvas.getContext("2d");
      // let img = new Image();
      // img.src = this.img_url;
    },
    //点击隐藏路径时候的跳转
    goToThisUrl(item){
      console.log("you click "+item.code);
      //清空可见路径，
      this.directoryList=[];
      //显示隐藏路径从点击的地方开始往前四个
      if(this.directoryListOlder.length>=4){
        for(let i=0;i<4;i++){
          this.directoryList.unshift(this.directoryListOlder.pop());
        }
      }else {
        for(let i=0;i<=this.directoryListOlder.length;i++){
          this.directoryList.unshift(this.directoryListOlder.pop());
        }
      }


      this.queryParams.pcode=item.code;
      listFlie(this.queryParams).then(response => {
        this.flieList = response.rows;
        this.total = response.total;
        this.pcode = item.pcode;
        this.loading = false;
      });
    },
    handleChange() {
    },
    submitZipUpload() {
      this.$refs.upload.submit();
    },


    handleFileZipUploadProgress(event, file, fileList) {
      this.uploadZip.isUploading = true;
      this.uploadZip.isUploading = true;
    },
// 文件上传成功处理
    handleZipFileSuccess(response, file, fileList) {
      this.uploadZip.isUploading = false;
      this.uploadZip.filePath = response.url;
      this.msgSuccess(response.msg);
      this.getList();
      this.refresh();
      this.created();

    },
    //点击选择标签
    handleclickTag(tag){
      console.log("点击了tag");
      var flag=true;
      if (this.fileObject.selectedLabel.length>0){
        for(var i=0;i<this.fileObject.selectedLabel.length;i++){
          if(tag==this.fileObject.selectedLabel[i]){
            flag=false;
            break;
          }
        }
        if(flag==true){
          this.fileObject.selectedLabel.push(tag);
        }
      }else {
        this.fileObject.selectedLabel.push(tag);
      }

    },
    //关闭标签
    handleTagClose(tag) {
      this.labelList.splice(this.labelList.indexOf(tag), 1);
    },
    //获取已有的标签
    getLabelList() {
      this.loading = true;
      listLabel().then(response => {
        this.labelList = response;
        this.loading = false;
      });
    },
    showZipFile() {
      this.fileObject.pcode = this.directoryList[this.directoryList.length-1].code;
      this.fileObject.selectedLabel=[];
      this.reset();
      this.uploadZip.fileList = [];
      this.getLabelList();
      this.openZipFile = true;
      this.openFile = false;
      // this.title = "上传文件夹"
    },
    // 处理文件大小
    calculateFileSize(row,column) {
      // console.log(row)
      let file_size = row[column.property];
      let  count  = 0;
      if (file_size == 0){
        return  "";
      }
      while (file_size > 1024 && count++ < 5){
        file_size /= 1024;
      }
      file_size = file_size.toFixed(2);
      if (count == 0){
        file_size += "Byte";
      }else if (count == 1){
        file_size += " KB";
      }else if (count == 2){
        file_size += " GB";

      }else if (count == 3){
        file_size += " TB";
      }else {
        file_size += " PB";
      }
      return file_size;
    },
    /** 初始化目录树*/
    handleSelectTree(){
      getSelectTree().then(response => {
        this.materialOptions = response.data
      })
      getLabelSelectTree().then(response=>{
        this.allLabelOptions=response
      })
    },
    /** 点击链接 */
    handleLink(item){
      this.reset();
      const code = item.code;
      this.queryParams.pcode = code;
      const  list =  this.directoryList;
      let  i=0;
      let first;
      for(;i<list.length;i++){
        if (list.length == 1){
          break;
        }
        if(item.code == list[i].code){
          for (let  j= i+1;j<list.length;j++){
            list.pop();
            if(this.directoryListOlder.length>0){
              first=this.directoryListOlder.pop();
              list.unshift(first);//向数组的开头添加一个或更多元素，并返回新的长度。
            }
          }
        }
      }
      this.loading = true;
      listFlie(this.queryParams).then(response => {
        this.flieList = response.rows;
        this.total = response.total;
        this.pcode = item.pcode;
        this.loading = false;
      });

    },
// 文件提交处理
    submitUpload() {
      this.$refs.uploadImg.submit();
      this.$refs.uploadTxt.submit();
      this.$refs.uploadZip.submit();
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.uploadImg.isUploading = true;
      this.uploadTxt.isUploading = true;
      this.uploadZip.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadImg.isUploading = false;
      this.uploadTxt.isUploading = false;
      this.uploadZip.isUploading = false;
      this.uploadImg.filePath = response.url;
      this.uploadTxt.filePath = response.url;
      this.uploadZip.filepath = response.url;
      this.msgSuccess(response.msg);
      this.getList();
      this.refresh();
      this.created();
    },
    uploadImgBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 100
      if (!isRightSize) {
        this.$message.error('文件大小超过 100MB')
      }
      let isAccept = new RegExp('image/*').test(file.type)
      let isAccept2 = new RegExp('video/*.mp4').test(file.type)
      if (!isAccept&&!isAccept2) {
        this.$message.error('应该选择image/*或video/*.mp4类型的文件')
      }
      return isRightSize && isAccept||isAccept2
    },
    uploadZipBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('text/plain').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择.txt类型的文件')
      }
      return isRightSize && isAccept
    },
    uploadTxtBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('text/plain').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择.txt类型的文件')
      }
      return isRightSize && isAccept
    },
    // 对文件与文件夹的处理
    showSwiper (row) {
      if (row === ''){
        return false;
      }
      if(row.contentType.startsWith("folder")){
        return true;
      }else {
        return  false;
      }

    },
    /** 汇总信息 **/
    getTotals() {
      getTotal().then(response => {
        this.fileTotalInfo = response.data;
      });
    },
    /**  */
    getList() {
      this.loading = true;
      listFlie(this.queryParams).then(response => {
        this.flieList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getTotals();
    },
    // 文件类型字典翻译
    contentTypeFormat(row, column) {
      return this.selectDictLabel(this.contentTypeOptions, row.contentType);
    },
    // 取消按钮
    cancel() {
      this.openFile = false;
      this.openDir = false;
      this.openShow = false;
      if(this.openShow==false){
        this.img_url="";
        this.tagImageUrl="";
      }
      this.open = false;
      this.openZipFile = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        originalFileName: null,
        contentType: null,
        fileSize: null,
        pathFileName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        pcode: null,
        code:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.label="";
      this.queryParams.pageNum = 1;
      let  i = 0;
      for (;i<this.queryParams.paramLabels.length;i++) {
        this.queryParams.label += this.queryParams.paramLabels[i]+" ";
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.label="";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 上传文件按钮操作 */
    handleAddFile() {
      this.fileObject.pcode = this.directoryList[this.directoryList.length-1].code;
      this.fileObject.selectedLabel=[];
      this.reset();
      this.uploadImg.fileList = [];
      this.uploadTxtfileList = [];
      this.openFile = true;
      // this.title = "上传文件";
      this.getLabelList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getFileLabel(id).then(response=>{
        this.fileObject.selectedLabel=response;
      });
      getFlie(id).then(response => {
        // console.log(response.data);
        this.form = response.data;
        this.open = true;
        this.title = "修改文件记录";
      });

    },
    /** 新增文件夹按钮操作 */
    handleAdd() {
      this.fileObject.pcode = this.directoryList[this.directoryList.length-1].code;
      this.reset();
      this.open = true;
      this.title = "添加文件夹";
    },
    /** 后退按钮 */
    handleBack() {
      this.reset();
      const code = this.pcode;
      this.queryParams.pcode = code;
      let x;
      if (this.directoryList.length != 1){
        x=this.directoryList.pop();
        this.queryParams.pcode =this.directoryList[this.directoryList.length-1].code;
        if(this.directoryListOlder.length>0){
          let first=this.directoryListOlder.pop();
          this.directoryList.unshift(first);//向数组的开头添加一个或更多元素，并返回新的长度。
        }
      }

      // this.getList();
      listFlie(this.queryParams).then(response => {
        this.flieList = response.rows;
        this.total = response.total;
        this.pcode = code;
        this.loading = false;
      });
    },
    //点击文件夹
    handleLook(row){
      if(this.directoryList.length+1>4){
        let firstDire=this.directoryList.shift(); //移除最前一个元素并返回该元素值，数组中元素自动前移
        this.directoryListOlder.push(firstDire);
        this.directoryListOlder.isNotEmpty=true;
        console.log(this.directoryListOlder);
      }
      this.directoryList.push({pcode: row.pcode,code:row.code,name:"/"+row.originalFileName})

      this.reset();
      const code = row.code;
      this.queryParams.pcode = code;
      this.getList();
    },
    /** 预览图片*/
    handlePreview(row){
      if(row.contentType.startsWith("video")){

        this.title = "视频预览";
        this.video_url  = process.env.VUE_APP_BASE_API +row.pathFileName;
        this.openShowVedio = true;
      }else if(
        row.contentType.startsWith("image")){
        this.img_url = process.env.VUE_APP_BASE_API +row.pathFileName;
        this.title = "预览图片";
        // this.getTagList(row);
        this.queryTagParams.fileCode=row.id;
        // this.loading=true;
        getTagImage(this.queryTagParams).then(response=>{
          this.tagImageUrl=process.env.VUE_APP_BASE_API +response;
          // this.loading=false;
          this.openShow = true;
        })

      }

    },
    /** 获取编辑图片的信息 **/

    /** 画矩形 提供点的坐标 颜色 粗细 绘制图片 画布 */

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            let param= new URLSearchParams()
            param.append("p_code",this.fileObject.pcode)
            param.append("labels",this.fileObject.selectedLabel)
            // console.log("params"+this.form.pcode)
            updateFlie(this.form,param).then(response => {
              // console.log("this.fileObject.pcode=="+this.fileObject.pcode)
              // console.log("params"+param)
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.handleSelectTree();

            });
          } else {
            this.form.contentType = "folder";
            this.form.pcode = this.fileObject.pcode;
            addFlie(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.handleSelectTree();
            });
          }
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除文件记录-2编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFlie(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    onOpen() {},
    onClose() {
      this.$refs['fileForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    /** 确认按钮 **/
    handelConfirm() {
      this.$refs['fileForm'].validate(valid => {
        if (!valid) return
        this.close()
      })
    },

    // 文件下载处理
    handleDownload(row) {
      var fileId=row.id;
      if (row.contentType == 'folder'){
        downloadFlie(fileId).then(response => {
          const aLink =document.createElement('a')
          const blob = new Blob([response], { type: 'application/zip' })
          let fileName = row.originalFileName +".zip"
          aLink.href = window.URL.createObjectURL(blob)
          aLink.setAttribute('download', fileName)
          document.body.appendChild(aLink)
          aLink.click()
          document.body.appendChild(aLink)
        }).catch(error => this.$message.error(error));
        return;
      }
      getTableFlie(fileId).then(response =>{
        this.tag_id = response.data.id;
        this.tag_name = response.data.originalFileName;
        // 标记文本下载
        downloadFlie(this.tag_id).then(response => {

          let blob = new Blob([response], {
            type: "application/octet-stream;charset=utf-8"
          });
          let fileName = this.tag_name;
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName);
          } else {
            var link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            //释放内存
            window.URL.revokeObjectURL(link.href);
          }
        })
          .catch(error => {
            console.log(error);
          });
      });
      // 素材的下载
      downloadFlie(fileId).then(response => {

        let blob;

        let fileName = row.originalFileName;

          blob = new Blob([response], {
            type: "application/vnd.ms-excel;charset=utf-8"
          });

        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          var link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          //释放内存
          window.URL.revokeObjectURL(link.href);
        }
      })
        .catch(error => {
          console.log(error);
        });
    },

    /** 查询标记文件信息列表 在图片上进行标记 */
    getTagList(row) {
      this.queryTagParams.fileCode=row.id;
      // this.queryTagParams.imgWidth=img.width;
      // this.queryTagParams.imgHeight=img.height;
      listTag_file(this.queryTagParams).then(response => {
        this.tag_fileList = response.rows;
        this.tag_total = response.total;
        var canvas = document.getElementById("mycanvas")
        // 由于弹窗，确保已获取到
        var a = setInterval(() =>{
          // 重复获取
          canvas = document.getElementById("mycanvas")
          clearInterval(a);
          if(!canvas){
            return false
          } else {
            // 可以理解为一个画笔，可画路径、矩形、文字、图像
            var context = canvas.getContext('2d');
            var img = new Image();
            img.src = this.img_url;
            let tag = this.tag_fileList;
            // 加载图片
            img.onload = function(){
              if(img.complete){
                // 根据图像重新设定了canvas的长宽
                canvas.setAttribute("width",img.width== null?1000:img.width);
                canvas.setAttribute("height",img.height==null?1000:img.height);
                // 绘制图片
                context.drawImage(img,0,0,img.width,img.height);
                // 绘制矩形
                var i ;
                let dw=img.width
                let dh=img.height
                for(i = 0 ;i<tag.length;i++){
                    let points = tag[i].tagInfo.split(" ");
                    /*
                    // let points = tag[i].tagInfo.split(",");//x,y,w,h
                    //绘制矩形
                    // context.strokeStyle = '#' + Math.random().toString(16).substr(2, 6).toUpperCase();
                  context.strokeStyle ='#FF0000'
                    context.lineWidth = 2;
                    // context.strokeRect(points[0], points[1], Math.abs(points[2]-points[0]), Math.abs(points[3]-points[1]));
                  console.log(points[0]+"==="+points[1]+"==="+points[2]+"==="+points[3]);
                    let center_x=Math.round(points[0].replace('[', '')*dw)
                    let center_y=Math.round(points[1].trim()*dh)
                    let bbox_width=Math.round(points[2].trim()*dw)
                    let bbox_height=Math.round(points[3].replace(']', '')*dh)
                  console.log(center_x+"----"+center_y+"----"+bbox_width+"----"+bbox_height);
                    let xmin=(center_x-bbox_width)/2;
                    let ymin=(center_y-bbox_height)/2
                    let xmax=(center_x+bbox_width)/2;
                    let ymax=(center_y+bbox_height)/2
                  console.log(xmin+"   "+ymin+"   "+Math.abs(xmax-xmin)+"   "+Math.abs(ymax-ymin))
                  let x0=center_x-Math.abs(xmax-xmin)/2;
                  let y0=center_y-Math.abs(ymax-ymin)/2;
                  console.log("test=="+x0+" "+y0);
                    // context.strokeRect(points[0].replace('[', '')*dw, points[1]*dh, points[2]*dw, points[3].replace(']', '')*dh);
                    context.strokeRect(x0, y0, Math.abs(xmax-xmin), Math.abs(ymax-ymin));
                     */
                  context.strokeStyle ='#FF0000'
                  context.lineWidth = 2;
                  let info=transferYolo(points[0].replace('[', ''),points[1].trim(),points[2].trim(),points[3].replace(']', ''),dw,dh);//转化标记文件yolo数值为坐标值
                  context.strokeRect(info.x0, info.y0, info.w, info.h);
                    context.font = "22px Arial bolder";
                    context.fillStyle = 'white';
                    context.fillText(tag[i].tagCategory,info.x0, info.y0)
                }
              }
            }
          }
        },1);
      });
    },



  },

  /* 下载文件的公共方法，参数就传blob文件流*/
  handleExport(data) {
    // 动态创建iframe下载文件
    let fileName = "1111";
    if (!data) {
      return;
    }
    let blob = new Blob([data], { type: "application/octet-stream" });
    if ("download" in document.createElement("a")) {
      // 不是IE浏览器
      let url = window.URL.createObjectURL(blob);
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); // 下载完成移除元素
      window.URL.revokeObjectURL(url); // 释放掉blob对象
    } else {
      // IE 10+
      window.navigator.msSaveBlob(blob, fileName);
    }
  },
  // 处理文件大小
  handleFileSize(file_size) {
      let  count  = 0;
      while (file_size > 1024 && count++ < 6){
          file_size /= 1024;
      }
      file_size = file_size.toFixed(2);
    if (count == 1){
      file_size += "Byte";
    }else if (count == 2){
      file_size += " KB";
    }else if (count == 3){
      file_size += " GB";

    }else if (count == 4){
      file_size += " TB";
    }else {
      file_size += " PB";
    }
    return file_size;
  },
  //鼠标按下时执行
  mousedown(e) {
    this.isMouseDownInCanvas = true;
    // 鼠标按下时开始位置与结束位置相同
    // 防止鼠标在画完矩形后 点击图画形成第二个图形
    this.endX = e.offsetX;
    this.endY = e.offsetY;
    this.startX = e.offsetX;
    this.startY = e.offsetY;
    this.mousemove(e)

  },
  //鼠标移动式时执行
  mousemove(e) {
    if (this.isMouseDownInCanvas) { // 当鼠标有按下操作时执行

      this.endX = e.offsetX;
      this.endY = e.offsetY;
      let wwidth = this.endX - this.startX;
      let wheigth = this.endY - this.startY;

      // 清除指定区域的所有像素
      this.customcxt.clearRect(0, 0, this.DivWidth, this.DivHeight);
      this.customcxt.strokeStyle = " #00ff00"; //矩形框颜色
      this.customcxt.lineWidth = "2";  //矩形框宽度
      this.customcxt.strokeRect(this.startX, this.startY, wwidth, wheigth);  //绘制矩形

    }
  },
  //鼠标松开时执行
  mouseup(e) {
    this.isMouseDownInCanvas = false;
  },

  Mouseleave(e) {
    this.isMouseDownInCanvas = false
  },

};


</script>
